<?php
namespace app\index\controller;

use think\Controller;

class common extends Controller
{
    /**
     *  获取用户信息
     */
    public function get_user()
    {
        $user_id = input("user_id");
        $model = model("Admin");
        $data = [];
        $user = $model->where(["id" => $user_id])->field("id,username,nickname,nickname,phone,email,role_id")->find();
        if (!empty($user)) {
            $data = $user;
        }

        return json($data);
    }

    public function export_week()
    {
        $request = request();
        $domain = $request->domain();
        $url = $domain . "/Index/Home/test";
        $info = file_get_contents($url);
        $str = "";
        preg_match("/<body[^>]*?>(.*\s*?)<\/body>/is", $info, $str);
        $str = $str[0];

        ob_start(); //打开缓冲区

        echo '
        <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" >
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <xml><w:WordDocument><w:View>Print</w:View></xml>
        </head>';
        echo $str;
        header("Cache-Control: no-store"); //所有缓存机制在整个请求/响应链中必须服从的指令
        Header("Content-type: application/octet-stream"); //用于定义网络文件的类型和网页的编码，决定文件接收方将以什么形式、什么编码读取这个文件
        Header("Accept-Ranges: bytes"); //Range防止断网重新请求 。
        if (strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE')) {
            header('Content-Disposition: attachment; filename=test.doc');
        } else if (strpos($_SERVER["HTTP_USER_AGENT"], 'Firefox')) {
            Header('Content-Disposition: attachment; filename=test.doc');
        } else {
            header('Content-Disposition: attachment; filename=test.doc');
        }
        header("Pragma:no-cache"); //不能被浏览器缓存
        header("Expires:0"); //页面从浏览器高速缓存到期的时间分钟数，设定expires属性为0，将使对一页面的新的请求从服务器产生
        ob_end_flush(); //输出全部内容到浏览器

    }
    /**
     * 登录
     */
    public function login()
    {
        if (request()->instance()->isPost()) {
            $post = request()->instance()->param();
            if (empty($post["username"])) {
                $this->error("用户名不能为空");
            }
            if (empty($post["userpwd"])) {
                $this->error("用户密码不能为空");
            }
            $result = model("Admin")->login($post["username"], $post["userpwd"]);
            if ($result) {

                $this->success("登录成功", url("/index/home/index"),"redirect");
            } else {
                $this->error("登录失败，用户或密码错误");
            }
        }
        return view("public/login");
    }

    public function logout()
    {
        session("user_id", null);
        session("user_menu", null);
        session_destroy();

        $this->redirect(url("Index/common/login"));
    }

    /**
     *
     */
    public function week_info()
    {
        $projetc_id = input("projetc_id");
        $week_id = input("week_id");
        $member_id = input("member_id");
        $projectWeek = model("ProjectWeekly");
        $product = model("WeekProduct");
        $project = model("Project");
        $member = model("Admin");
        $team = model("Team");
        $pm_info = [];
        $product_list = [];
        $projectWeek_info = [];
        $team_list = [];
        $project_info = $project->where(["id" => intval($projetc_id)])->find();
        if (!empty($project_info)) {
            $pm_info = $member->where(["id" => intval($project_info["pm_uid"])])->find();
            $projectWeek_info = $projectWeek->where(["id" => $week_id, "project_id" => $projetc_id, "uid" => $member_id])->find();
            if (!empty($projectWeek_info)) {
                $product_list = $product->where(["week_id" => $week_id, "project_id" => $projetc_id])->select();
            }
            $team_list = $team->where(["project_id" => intval($projetc_id)])->with("user")->select();

        }
        $data["project_info"] = $project_info;
        $data["pm_info"] = $pm_info;
        $data["projectWeek_info"] = $projectWeek_info;
        $data["product_list"] = $product_list;
        $data["team_list"] = $team_list;
        $this->assign($data);
        return view("public/week");
    }

    public function weekpm()
    {
        $week = input("week");
        if (empty($week)) {
            $week = date('W', time());
        }
        $member = model("Admin"); //用户信息
        $project = model("project"); //项目

        $project_weekly = model("ProjectWeekly"); //周报
        $week_product = model("WeekProduct"); //周报产品信息
        $monthly = model("monthly"); //月报
        $project_list=[];
        $week_list=[];
        $monthly_list=[];
        $project_list = $project->field("id,title,pm_uid")->select()->toArray();
        //项目经理id
        $pm_ids = array_column($project_list, "pm_uid");
   
        if (!empty($pm_ids)) {       
            //获取周报
            $week_list = $project_weekly->where(["uid" => array("in", $pm_ids), "weeks" => $week])->select()->toArray();
       
            $week_ids = array_column($week_list, "id");
            if (!empty($pm_ids)) {
                //获取月报信息
                $monthly_list = $monthly->where(["week_id" => array("in", $week_ids)])->select()->toArray();
            
            }
        }
        $data["project_list"] = $project_list;
        $data["week_list"] = $week_list;
        $data["monthly_list"] = $monthly_list;
        $data["week"] = $week;
        $this->assign($data);
        return view("public/weekpm");
    }
    //上传文件
    public function uploadfile()
    {
        $oldfile = $_FILES;
        $file = request()->file('file');
        $fileext = "*.png,*.jpg,*.pdf,*.txt,*.doc,*.docx,*.xlsx,*.xls";
        $filelen = 204800;
        $data['filename'] = "";
        $data['savename'] = "";
        $data['fileid'] = 0;

        $objtype = isset($_POST['objtype']) ? $_POST['objtype'] : "";
        $n = 0;
        $fileid = "";

        // 移动到框架应用根目录/public/uploads/ 目录下

        $oldName = $oldfile['file']["name"];
        $size = $oldfile['file']["size"];

        $ext = "." . pathinfo($oldfile['file']["name"], PATHINFO_EXTENSION);

        if (stristr($fileext, $ext)) {
            if ($size <= $filelen) {
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                //print_r($info);die();

                if ($info) {
                    $n = $n + 1;
                    $fileData['file_name'] = $oldName;

                    $fileData['save_name'] = $info->getFilename();
                    $fileData['save_path'] = '\public\uploads' . '\\' . $info->getSaveName();

                    //print_r($fileData['FilePath']);die();
                    //$fileData['FileExt'] = $ext;
                    $fileData['file_length'] = $size;
                    $fileData['obj_type'] = $objtype;
                    $fileModel = model("File");
                    $fileImte = $fileModel->save($fileData);

                    if ($fileImte) {
                        $data['filename'] = rtrim(ltrim($data['filename'] . "," . $oldName, ","), ",");
                        $data['savename'] = rtrim(ltrim($data['savename'] . "," . $fileData['save_path'], ","), ",");
                        $data['fileid'] = $fileModel->id;
                    } else {
                        $data['filename'] = " 文件保存失败!";
                        $data['status'] = "300";
                    }
                } else {
                    $data['savename'] = "";
                    $data['filename'] = $data['filename'] . " 文件保存失败";
                    $data['status'] = "300";
                }
            } else {
                $data['savename'] = "";
                $data['filename'] = $data['filename'] . " 文件太大";
                $data['status'] = "300";
            }

            if ($n) {
                $data['status'] = "200";
                $data['fileid'] = rtrim(ltrim($data['fileid'], ","), ",");
                $data['filename'] = rtrim(ltrim($data['filename'], ","), ",");
            } else {
                $data['status'] = "300";
            }

        } else {
            $data['savename'] = "";
            $data['filename'] = $data['filename'] . " 文件格式错误";
            $data['status'] = "300";
        }

        echo json_encode($data);
        die();
    }

}
